import {ChangeEvent, FC, useContext, useEffect, useRef, useState} from "react";
import Message from "../../../../models/Message";
import {UserContext} from "../../../../index";
import {getOldMessages, sendMessage, startSignalRConnection, stopSignalRConnection} from "../../../../http/chatApi";
import {getImageById} from "../../../../http/imageApi";
import handleImageNotLoaded from "../../../../functions/handleImageNotLoaded";
import './styles/Chat.css'
import {useNavigate} from "react-router-dom";
import routeNames from "../../../../utils/routeNames";

interface ChatProps {
    setOnlineUsers: (users: string[]) => void;
}

const Chat: FC<ChatProps> = ({setOnlineUsers}) => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputMessage, setInputMessage] = useState('');
    const userStore = useContext(UserContext)
    const [errorMessage, setErrorMessage] = useState('');
    const chatMessagesRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);
    const navigate = useNavigate()

    useEffect(() => {
        const handleReceiveMessage = (message: Message) => {
            setMessages(prevMessages => [...prevMessages, message]);
        };

        const handleConnectionUpdate = (onlineUsers: string[]) => {
            setOnlineUsers(onlineUsers);
        };

        startSignalRConnection(handleReceiveMessage, handleConnectionUpdate)
            .then(() => {
                getOldMessages()
                    .then(messages => {
                        setMessages(messages);
                    })
                    .catch(error => {
                        console.error('Ошибка при получении старых сообщений:', error);
                    });
            })
            .catch(error => {
                console.error('Ошибка при установке соединения SignalR:', error);
            });

        return () => {
            stopSignalRConnection();
        };
    }, []);

    const handleKeyDown = (e: KeyboardEvent) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            postMessage().catch(error => console.error("Sending message error:", error));
        }
    };

    useEffect(() => {
        if (inputRef.current) {
            inputRef.current.addEventListener('keydown', handleKeyDown as any);
        }

        return () => {
            if (inputRef.current) {
                inputRef.current.removeEventListener('keydown', handleKeyDown as any);
            }
        };
    }, [inputMessage]);

    useEffect(() => {
        if (chatMessagesRef.current) {
            chatMessagesRef.current.scrollTop = chatMessagesRef.current.scrollHeight;
        }
    }, [messages]);

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        let {value} = e.target;
        if (value.length >= 500) {
            value = value.slice(0, 500);
            setErrorMessage('Максимум 500 символов');
        } else {
            setErrorMessage('');
        }

        setInputMessage(value);
    };

    const postMessage = async () => {
        if (inputMessage.trim() === '') {
            return;
        }
        await sendMessage(inputMessage);
        setInputMessage('');
        setErrorMessage('');
    };

    return (
        <div className="chat-container">
            <div className="chat-header">
                <h1>Chat</h1>
            </div>
            <div className="chat-messages" ref={chatMessagesRef}>
                {messages.map(message => (
                    <div key={message.id}
                         className={`message ${message.senderName === userStore.user.username ? 'my-message' : ''}`}>
                        <img src={getImageById(message.senderImageId)} alt="Avatar" className="avatar"
                             onError={handleImageNotLoaded}/>
                        <div className="message-content">
                            <div className="message-sender" onClick={() => navigate(routeNames.USER_PAGE, {state: {userId: message.whoSentId}})}>{message.senderName}</div>
                            <div className="message-text">{message.text}</div>
                        </div>
                    </div>
                ))}
            </div>
            <div className="chat-input">
                {errorMessage && <div className="error-message">{errorMessage}</div>}
                <input
                    type="text"
                    placeholder="Type your message..."
                    value={inputMessage}
                    onChange={(e) => handleInputChange(e)}
                    ref={inputRef}/>
                <button onClick={postMessage}>Send</button>
            </div>
        </div>
    );
}

export default Chat